import axios from "axios";
import { useStore } from '@/store/index';
import { storeToRefs } from "pinia";

import { showToast } from 'vant';
let instance = axios.create({
  timeout: 30000,
  baseURL: import.meta.env.VITE_APP_API
});


instance.interceptors.request.use(
  (config) => {
    const store = useStore();
    const { accessToken, userInfo } = storeToRefs(store)    
    var token = userInfo.token || accessToken.value ||  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjo0OTI5LCJsb2dpbl90eXBlIjo0LCJvcGVuSWQiOiIiLCJzZXJ2ZXJfbW9kZSI6ImRlYnVnIiwiaXNzIjoiYXhlX21hZ2ljX21pcnJvciIsImV4cCI6MTczNTExNzIyMX0.jcGbZT9T6ns-8EWe0WsKCztUge9-6XbqnhPbZxbZ5qo' || "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjo0MDE1LCJsb2dpbl90eXBlIjoxLCJvcGVuSWQiOiJvY3FnajZRTU1ZWFdGUjdqVmU1d3dmdWR0UlB3Iiwic2VydmVyX21vZGUiOiJkZWJ1ZyIsImlzcyI6ImF4ZV9tYWdpY19taXJyb3IiLCJleHAiOjE3MzQ4Mzg2NzR9.siZ-e0Xjg4iWVkJjdp4KR6xsH_tnM3DaVrZmSwolkDk"
    console.log(token, '请求所用的token')
    if (token) {
      config.headers["token"] = token;
    }

    return config;
  },
  error => {
    console.log(error, "请求拦截error")
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  response => {
    const res = response.data;
    const store = useStore();
    if (res.code !== 1000) {
      showToast({
        message: `${res.msg}`,
        position: "bottom",
        duration: 2000
      });
    }
    if (res.code === 1012 || res.code === 2003) {
      // 身份过期,请重新登录
      showToast('登录失效,请刷新页面重试')
      store.setLoginStatus(0)
      store.setAccessToken('')
      // await store.dispatch('setRefreshToken', refresh_token)
      store.setUserInfo({})
      window.location.reload()
      // const timer = setTimeout(() => {
      //     clearInterval(timer);
      //     Toast.clear();
      // }, 3000);

      return
    }
    return res;
  },
  error => {
    console.log(error, "响应拦截   error")

    if (error && error.response) {
      switch (error.response.status) {
        case 500:
          showToast({
            message: `服务器内部错误`,
            position: "bottom"
          });
          break;
      }
    }
    return Promise.reject(error);
  }
);
class Http {
  static async get(url, params) {
    return await instance.get(url, { params });
  }
  static async post(url, params) {
    return await instance.post(url, params);
  }
}

export default Http;
